package com.example.demo8.controller;

import com.example.demo8.dto.LoginDto;
import com.example.demo8.po.User;
import com.example.demo8.service.UserService;
import com.example.demo8.util.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

    @Resource
    private UserService userService;

    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        User user = userService.getByUsername(username);
        if (user == null) {
            return Result.fail("用户名不存在");
        }
        if (!user.getPassword().equals(password)) {
            return Result.fail("密码不正确");
        }
        return Result.ok();
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "退出";
    }


}
